/**
 * @author kan
 */

$(function(){
    $("button").button();

    var colNames = ['Image ID', 'Image Type', 'Architecture', 'Platform', 'Location'];
    var colModels = [
    {
        name: "imageId",
        index: "imageId",
        width: 150
    },
    {
        name: "imageType",
        index: "imageType",
        width: 150
    },
    {
        name: "arch",
        index: "arch",
        width: 100
    },
    {
        name: "platform",
        index: "platform",
        width: 80
    },
    {
        name: "location",
        index: "ref",
        width: 500
    },
    ];

    var imagesGrid = createGrid("images", colNames, colModels);

    $("#run-instance-btn").click(function(){
        var keypairs = getJSON("keypairs/name.json");
        var securityGroups = getJSON("security_groups/name.json");
        
        var keypairSelect = createSelectOptions("keypair-select", keypairs);
        var securityGroupSelect = createSelectOptions("security-group-select", securityGroups);
        var typeSelect = createSelectOptions("type-select", [
            "m1.small",
            "c1.medium",
            "m1.large",
            "m1.xlarge",
            "c1.xlarge"
        ]);
        
        var id = imagesGrid.jqGrid("getGridParam", "selrow");
        if (!id){
            showErrorDialog("Please select an image!");
            return;
        }

        var data = imagesGrid.jqGrid("getRowData", id);
        if (data.imageType != "machine"){
            showErrorDialog("Please select a machine image!");
            return;
        }

        $("#run-instance-dialog-id").html(data.imageId);

        var runInstanceDialog = $("#run-instance-dialog").dialog({
            modal: true,
            resizable: false
        });
        
        $("#run-instance-dialog-submit").click(function() {
            var data = {
                keypair: keypairSelect.val(),
                securityGroup: securityGroupSelect.val(),
                type: typeSelect.val(),
                number: $("#number-input").val()
            }
            console.dir(data);
            
            runInstanceDialog.dialog("close");
            $("#instances-td").click();
        });
    });
});